package com.group.view;


import com.group.controller.StudentController;
import com.group.model.Student;

import javax.swing.*;
import java.awt.*;
import java.util.Map;

/**
 * @author lenovo
 */
public class EditScorePanel extends JPanel {
    private JTextField idField = new JTextField();
    private JTextField courseField = new JTextField();
    private JTextField newScoreField = new JTextField();

    private JLabel statusLabel = new JLabel();

    public EditScorePanel() {
        setLayout(new GridLayout(5, 2, 5, 5));

        add(new JLabel("学号：")); add(idField);
        add(new JLabel("课程名（Math/Java/PE）：")); add(courseField);
        add(new JLabel("新成绩（留空表示删除该课程成绩）：")); add(newScoreField);

        JButton updateBtn = new JButton("修改/删除成绩");
        add(updateBtn); add(statusLabel);

        updateBtn.addActionListener(e -> {
            String id = idField.getText().trim();
            String course = courseField.getText().trim();
            String newScoreText = newScoreField.getText().trim();

            Student s = StudentController.get(id);
            if (s == null) {
                statusLabel.setText("未找到该学号的学生！");
                return;
            }

            Map<String, Double> scores = s.getScores();

            if (newScoreText.isEmpty()) {
                // 删除成绩
                if (scores.containsKey(course)) {
                    s.addScore(course, 0.0);
                    statusLabel.setText("成绩已删除！");
                } else {
                    statusLabel.setText("该课程成绩不存在");
                }
            } else {
                // 修改成绩
                try {
                    double score = Double.parseDouble(newScoreText);
                    if (score < 0 || score > 100) {
                        statusLabel.setText(" 成绩必须在 0-100 之间！");
                        return;
                    }
                    s.addScore(course, score);
                    statusLabel.setText(" 成绩已修改！");
                } catch (NumberFormatException ex) {
                    statusLabel.setText(" 输入的成绩不是合法数字！");
                }
            }

            try {
                StudentController.saveToFile("saveStudents.txt");
            } catch (Exception ex) {
                //
            }
        });
    }
}
